<script setup>
import {
  Delete,
  Edit,
  Search,
  Refresh,
  Picture,
} from "@element-plus/icons-vue";
import { ref } from "vue";
import {
  expClassListService,
  expClassDeleteService,
  expClassUpdateStatusService,
} from "@/api";
import { formatTime, formatStutas } from "@/utils/format";
import ExpClassEdit from "./components/ExpClassEdit.vue";
import { useUserStore } from "@/stores";

const userInfo = useUserStore();

// 列表数据
const articleList = ref([]);
const total = ref(0);
const loading = ref(false);

// 搜索参数
const params = ref({
  pageNum: 1,
  pageSize: 10,
  createTimeBegin: "",
  createTimeEnd: "",
  categoryName: "",
  status: "",
});
// 状态选项
const options = [
  { label: "正常", value: 1 },
  { label: "禁用", value: 0 },
];
// 获取数据
const getArticleList = async () => {
  loading.value = true;
  const { data } = await expClassListService(params.value);
  console.log(data);
  articleList.value = data.records;
  total.value = data.total;
  loading.value = false;
};
getArticleList();

// 删除操作------start
/**
 * 删除文章
 * @param {Object} row - 文章对象，包含文章信息，至少包含文章标题和ID
 * @returns {Promise<void>} 不返回任何内容
 */
const onDeleteArticle = async (row) => {
  // 打印待删除文章的信息
  console.log(row);
  let ids = [+row.id];

  // 显示删除确认框
  await ElMessageBox.confirm(
    `你确认删除“${row.categoryName}”这个分类吗？`,
    "温馨提示",
    {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }
  );
  loading.value = true;

  // 调用文章删除服务
  await expClassDeleteService(ids);

  // 显示删除成功的消息
  ElMessage({ type: "success", message: "删除成功" });

  // 重新获取文章列表
  getArticleList();
};
// 删除操作------end

// 添加或编辑时打开抽屉------start
// 获得抽屉ref
const userEditRef = ref();

// 添加文章
const onAddArticle = () => {
  userEditRef.value.open({}, "add");
};

// 编辑
const onEditArticle = (row, operate) => {
  userEditRef.value.open(row, operate);
};

// 添加修改成功
const onSuccess = (type) => {
  if (type === "add") {
    // 如果是添加，需要跳转渲染最后一页，编辑直接渲染当前页
    const lastPage = Math.ceil((total.value + 1) / params.value.pageSize);
    params.value.pageNum = lastPage;
  }
  getArticleList();
};
// 添加或编辑时打开抽屉------end

// 搜索-------start
const onSearch = () => {
  params.value.pageNum = 1;
  getArticleList();
};

// 重置搜索
const onReset = () => {
  reset();
  getArticleList();
};
// 搜索-------end

/**
 * 重置表单内容
 */
const reset = () => {
  params.value = {
    pageNum: 1,
    pageSize: 5,
    createTimeBegin: "",
    createTimeEnd: "",
    categoryName: "",
    status: "",
  };
};

// 分页：改变每页显示的页数-------start
const onSizeChange = (size) => {
  params.value.pageNum = 1;
  params.value.pageSize = size;
  getArticleList();
};
/**
 * 当当前页发生变化时的处理函数
 * 主要用于更新请求参数中的页码，并重新获取文章列表。
 *
 * @param {number} page - 新的当前页码
 */
const onCurrentChange = (page) => {
  // 更新参数中的页码
  params.value.pageNum = page;
  // 调用获取文章列表的函数
  getArticleList();
};
// 分页：改变每页显示的页数-------end

// 切换用户状态-----start
// 初始化一个用于表示加载状态的ref对象，初始值为false
let loadingStatusId = ref(null);
/**
 * 用于处理用户状态更改的异步函数
 * @param row 包含行数据的对象，此对象应包含状态和ID属性
 * @returns Promise
 */
const onStatusChange = async (row) => {
  try {
    loadingStatusId.value = row.categoryId;
    // 根据当前行的状态，确定要更新的新状态
    row.status = row.status == 0 ? 1 : 0;
    await expClassUpdateStatusService(row.categoryId, row.status);
    ElMessage.success("修改成功");
  } catch (error) {
    console.log(error);
    row.status = row.status == 0 ? 1 : 0;
  } finally {
    loadingStatusId.value = null;
  }
};
// 切换用户状态-----end
</script>
<template>
  <pageContainer title="表情分类">
    <template #extra>
      <el-button type="primary" @click="onAddArticle()">添加分类</el-button>
    </template>
    <el-form inline style="width: 100%" :model="params">
      <el-form-item label="分类名称：">
        <el-input
          placeholder="请输入分类名称"
          v-model="params.categoryName"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select
          style="width: 180px"
          placeholder="请选择状态"
          v-model="params.status"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创造时间：">
        <el-col :span="11">
          <el-date-picker
            v-model="params.createTimeBegin"
            type="date"
            placeholder="开始时间"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="2" style="text-align: center">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-date-picker
            v-model="params.createTimeEnd"
            placeholder="结束时间"
            style="width: 100%"
          />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="onSearch"
          >搜索</el-button
        >
        <el-button :icon="Refresh" @click="onReset()">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="articleList"
      style="width: 100%"
      v-loading="loading"
      border
    >
      <el-table-column label="序号" type="index" width="80" align="center">
      </el-table-column>
      <el-table-column label="分类名称" prop="categoryName"> </el-table-column>

      <el-table-column label="代表图片" prop="imageUrl" align="center">
        <template #default="{ row }">
          <el-image
            style="width: 80px; height: 80px; border: 1px solid #eee"
            :src="row.imageUrl"
            fit="cover"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
                暂无
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="description"></el-table-column>
      <el-table-column label="创造时间" prop="createTime">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="修改时间" prop="updateTime">
        <template #default="{ row }">
          {{ formatTime(row.updateTime, "YYYY年MM月DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template #default="{ row }">
          {{ formatStutas(row.status, "userManager") }}
          <el-switch
            :model-value="row.status === 1 ? true : false"
            :loading="loadingStatusId === row.categoryId"
            @change="onStatusChange(row)"
        /></template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="onEditArticle(row, 'edit')"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="onDeleteArticle(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 使用分页组件 -->
    <Pagination
      :currentPage="params.pageNum"
      :pageSize="params.pageSize"
      :total="total"
      :pageSizes="[10, 20]"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    />

    <!-- 抽屉 -->
    <ExpClassEdit ref="userEditRef" @success="onSuccess"></ExpClassEdit>
  </pageContainer>
</template>
<style lang="scss" scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  // font-size: 30px;
}
.image-slot .el-icon {
  font-size: 26px;
}
</style>
